const { connect } = require('../connectDatabase');

const {
  mysqlHandle,
  mysqlHandleCurry,
  setResponse,
  getSql,
  postSql,
  updateSql,
  deleteSql,
} = require('../utils');

const getInterface = async (req, res) => {
  let connection;
  const { fields, table, query } = req;
  const { queryField = {} } = query;
  let _queryField = {};
  const keysToKeep = Object.keys(queryField).filter((key) => key !== 'page' && key !== 'pageSize');
  // 使用剩余的键来复制属性
  keysToKeep.forEach((key) => {
    _queryField[key] = queryField[key];
  });
  const paging = {
    page: query?.page,
    pageSize: query?.pageSize,
  };
  try {
    connection = await connect();
    const excute = mysqlHandleCurry(mysqlHandle)(connection);
    let result = await excute(getSql(fields, paging, table));
    let total;
    if (paging.page && paging.pageSize) {
      total = await excute(`select count(*) as total from ${table}`);
    }
    Object.keys(_queryField).forEach((key) => {
      result = result.filter((item) => item[key] === queryField[key]);
    });
    const response = setResponse({
      code: 'SUCCESS',
      data: result,
      total: total[0].total,
      message: '',
      success: true,
    });
    if (!paging.page || !paging.pageSize) {
      delete response.total;
    }
    res.status(200).json(response);
  } catch (error) {
    const response = setResponse({
      code: 'FAILED',
      data: {},
      message: result.error,
      success: false,
    });
    res.status(500).json(response);
  } finally {
    if (connection) {
      connection.end();
    }
  }
};

const postInterface = async (req, res) => {
  let connection;
  try {
    const { fields, table } = req;
    const { url, title, publish_date } = req.body;
    connection = await connect();
    const excute = mysqlHandleCurry(mysqlHandle)(connection);
    const result = await excute(postSql(fields, table), url, title, publish_date);
    console.log('🚀 ~ postInterface ~ result:', result);
    if (!result.error) {
      const response = setResponse({
        code: 'SUCCESS',
        data: {},
        message: '',
        success: true,
      });
      res.status(200).json(response);
    } else {
      const response = setResponse({
        code: 'FAILED',
        data: {},
        message: result.error,
        success: false,
      });
      res.status(200).json(response);
    }
  } catch (error) {
    const response = setResponse({
      code: 'FAILED',
      data: {},
      message: error,
      success: false,
    });
    res.status(500).json(response);
  } finally {
    if (connection) {
      connection.end();
    }
  }
};

const putInterface = async (req, res) => {
  let connection;
  try {
    const { fields, table } = req;
    const { id, title, publish_date, url } = req.body;
    connection = await connect();
    const excute = mysqlHandleCurry(mysqlHandle)(connection);
    const result = await excute(updateSql(fields, table), url, title, publish_date, id);
    if (!result.error) {
      const response = setResponse({
        code: 'SUCCESS',
        data: {},
        message: '',
        success: true,
      });
      res.status(200).json(response);
    } else {
      const response = setResponse({
        code: 'FAILED',
        data: {},
        message: result.error,
        success: false,
      });
      res.status(200).json(response);
    }
  } catch (error) {
    console.log('🚀 ~ app.post ~ error:', error);
    const response = setResponse({
      code: 'FAILED',
      data: {},
      message: error,
      success: false,
    });
    res.status(500).json(response);
  } finally {
    if (connection) {
      connection.end();
    }
  }
};
const deleteInterface = async (req, res) => {
  let connection;
  try {
    const { fields, table } = req;
    connection = await connect();
    const excute = mysqlHandleCurry(mysqlHandle)(connection);
    await excute(deleteSql(fields, table), req.params.id);
    const response = setResponse({
      code: 'SUCCESS',
      data: {},
      message: '',
      success: true,
    });
    res.status(200).json(response);
  } catch (error) {
    const response = setResponse({
      code: 'FAILED',
      data: {},
      message: error,
      success: false,
    });
    res.status(500).json(response);
  } finally {
    if (connection) {
      connection.end();
    }
  }
};

module.exports = {
  getInterface,
  postInterface,
  putInterface,
  deleteInterface,
};
